package org.kumas.mybatissimple.executor.statement;

import org.kumas.mybatissimple.binding.MapperMethod;
import org.kumas.mybatissimple.executor.resultset.DefaultResultSetHandler;
import org.kumas.mybatissimple.executor.resultset.ResultSetHandler;
import org.kumas.mybatissimple.utils.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class SimpleStatementHandler implements StatementHandler {
    private ResultSetHandler resultSetHandler;

    public SimpleStatementHandler() {
        this.resultSetHandler = new DefaultResultSetHandler();
    }

    @Override
    public <T> T query(MapperMethod mapperMethod, Object parameter) throws SQLException {
        Connection connection = DbUtil.open();
        String sql = String.format(mapperMethod.getSql(), Integer.valueOf((String) parameter));
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.execute();
        try {
            return resultSetHandler.handle(preparedStatement, mapperMethod,parameter);
        } catch (Exception e) {
            throw new SQLException(e);
        }
    }
}